//
//  AppTools.m
//  AllMan
//
//  Created by dllo on 15/11/16.
//  Copyright © 2015年 Echo.Jobs. All rights reserved.
//

#import "AppTools.h"

@implementation AppTools


+(void)getDataWithURL:(NSString *)url Block:(AppToolsBlock)block ErrorBlock:(AppToolsErrorBlock)errorBlock
{
    NSString *urlEncode = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    //    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    
    //    NSString *url_string = [NSString stringWithFormat:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/activitylist.php"];
    
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    // 进行了两次UTF8转码,所以需要给他变回来
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:urlEncode parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        //        [netWorkManager stopMonitoring];
        //        NSLog(@"使用AFN进行get请求 ===  %@",responseObject);
#pragma mark - 缓存归档
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        // 存储的沙盒路径
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
        
        block(responseObject);

        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"失败==== %@",error);
        
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
        block(result);
        errorBlock(error);

        
    }];
    
}



@end
